package com.sh.data.engine.velocity;

import com.sh.data.engine.velocity.model.iotdb.IotDataModel;
import org.apache.commons.io.FileUtils;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.tools.ToolContext;
import org.apache.velocity.tools.ToolManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URL;
import java.util.List;
import java.util.UUID;

public class VelocityScriptEngine {

    private static final Logger logger = LoggerFactory.getLogger(VelocityScriptEngine.class);

    private static VelocityEngine ve;

    static {
        try {
            ve = new VelocityEngine();
            // 设置模板加载路径，这里设置的是class下
            ve.setProperty(Velocity.RESOURCE_LOADER, "class");
            ve.setProperty(
                "class.resource.loader.class",
                "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
            // 进行初始化操作
            ve.init();
        } catch (Exception e) {
            logger.error("init VelocityEngine error", e);
        }
    }

    public static List<IotDataModel> evel(String json, String script, String logTag) {
        logger.info("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
        logger.info("获取解析脚本成功:\n{}", script);
        ToolManager manager = new ToolManager();
        manager.configure("tools.xml");
        ToolContext context = manager.createContext();
        IotDataModel dataModel = new IotDataModel();
        dataModel.setJson(json);
        context.put("IOT_DATA_MODEL", dataModel);
        StringReader reader = new StringReader(script);
        StringWriter writer = new StringWriter(1024);
        ve.evaluate(context, writer, logTag, reader);
        Object obj = context.get("result");
        if (obj == null) {
            return null;
        }
        return (List<IotDataModel>) obj;
    }

    public static void main(String[] args) throws Exception {
        ClassLoader classLoader = VelocityScriptEngine.class.getClassLoader();
        URL jsonUrl = classLoader.getResource("test_json.json");
        URL scriptUrl = classLoader.getResource("test_script.vm");
        File jsonFile = new File(jsonUrl.getFile());
        File scriptFile = new File(scriptUrl.getFile());
        String json = FileUtils.readFileToString(jsonFile, "utf-8");
        String script = FileUtils.readFileToString(scriptFile, "utf-8");
        VelocityScriptEngine engine = new VelocityScriptEngine();
        List<IotDataModel> model = engine.evel(json, script, UUID.randomUUID().toString());
        System.out.println(model.toString());
    }
}
